package com.yhcui.monitor.logic;

import com.yhcui.monitor.bean.AppInfo;
import com.yhcui.monitor.task.MonitorTask;
import com.yhcui.monitor.task.PutTask;
import com.yhcui.monitor.task.SendMsgTask;
import org.springframework.stereotype.Component;

import java.util.concurrent.*;

/**
 * TODO 使用配置文件
 */
@Component
public class MonitorLogic {

    // 存放任务线程池
    private ScheduledExecutorService putExecutorService;

    // 进行监控线程池
    private ExecutorService monitorExecutorService;

    // 发送告警消息线程池
    private ExecutorService sendMsgExecutorService;

    // 队列
    private BlockingQueue<AppInfo> putTaskQueue;

    // 队列
    private BlockingQueue<AppInfo> sendMsgQueue;

    /**
     * 初始化存放任务、监控、发送信息的线程及队列
     * 后面优化可以放入线程池中进行管理
     */
    public void init() {
        putExecutorService = Executors.newScheduledThreadPool(1);

        monitorExecutorService = new ThreadPoolExecutor(0, 3,
                60L, TimeUnit.SECONDS,
                new SynchronousQueue<>());


        sendMsgExecutorService = new ThreadPoolExecutor(0, 1,
                5L, TimeUnit.SECONDS,
                new SynchronousQueue<>());

        putTaskQueue = new LinkedBlockingQueue<>();
        sendMsgQueue = new LinkedBlockingQueue<>();
    }

    /**
     * 启动各个任务
     */
    public void start() {

        putExecutorService.scheduleAtFixedRate(new PutTask(putTaskQueue), 5L,20, TimeUnit.SECONDS);
        monitorExecutorService.execute(new MonitorTask(putTaskQueue, sendMsgQueue));
        sendMsgExecutorService.execute(new SendMsgTask(sendMsgQueue));
    }

}
